<?php

class SettingsController extends BackendController
{
    public function filters()
    {
        $parent_filters = parent::filters();
        // $parent_filters[] = 'filterFunction';
        return $parent_filters;
    }


    public function actionClearCache($do_redirect = true)
    {
        Yii::app()->cache->flush();
        try
        {
            Notifier::clearCacheOnServers();
        }
        catch (Exception $e) {
        }

        if ($do_redirect) {
            $this->redirect(Yii::app()->user->returnUrl);
        }
    }

    public function actionEmailTemplates()
    {
        $cs = Yii::app()->clientScript;
        $cs->registerCoreScript('jquery');
        $cs->registerCoreScript('cookie');
        $cs->registerCoreScript('jquery.ui');
        $cs->registerCssFile(Yii::app()->request->baseUrl . '/css/redmond/jquery-ui.css');

        $et = new EmailTemplates();

        $change_pass_subject = Yii::app()->request->getPost('change_pass_subject');
        if ($change_pass_subject != null) {
            $templates_new['change_pass_subject'] = $change_pass_subject;
            $templates_new['change_pass_body'] = str_replace("\n", '<br>', Yii::app()->request->getPost('change_pass_body'));
            $templates_new['change_wmz_subject'] = Yii::app()->request->getPost('change_wmz_subject');
            $templates_new['change_wmz_body'] = str_replace("\n", '<br>', Yii::app()->request->getPost('change_wmz_body'));
            $templates_new['contact_subject'] = Yii::app()->request->getPost('contact_subject');
            $templates_new['contact_body'] = str_replace("\n", '<br>', Yii::app()->request->getPost('contact_body'));
            $templates_new['buy_premium_subject'] = Yii::app()->request->getPost('buy_premium_subject');
            $buy_premium_body_1 = str_replace("\n", '<br>', Yii::app()->request->getPost('buy_premium_body_1'));
            $buy_premium_body_2 = str_replace("\n", '<br>', Yii::app()->request->getPost('buy_premium_body_2'));
            $templates_new['buy_premium_body'] = $buy_premium_body_1 . "{premium-code}{account-info-text-if-new-acc}" . $buy_premium_body_2;
            $templates_new['reg_acc_body'] = str_replace("\n", '<br>', Yii::app()->request->getPost('reg_acc_body'));
            $templates_new['premium_code_body'] = str_replace("\n", '<br>', Yii::app()->request->getPost('premium_code_body'));
            $templates_new['news_subject'] = Yii::app()->request->getPost('news_subject');
            $templates_new['news_body'] = str_replace("\n", '<br>', Yii::app()->request->getPost('news_body'));
            $templates_new['old_files_subject'] = Yii::app()->request->getPost('old_files_subject');
            $templates_new['old_files_body'] = str_replace("\n", '<br>', Yii::app()->request->getPost('old_files_body'));
            $templates_new['del_files_subject'] = Yii::app()->request->getPost('del_files_subject');
            $templates_new['del_files_body'] = str_replace("\n", '<br>', Yii::app()->request->getPost('del_files_body'));

            $templates_new['change_new_user_subject'] = str_replace("\n", '<br>', Yii::app()->request->getPost('change_new_user_subject'));
            $templates_new['change_new_user_body'] = str_replace("\n", '<br>', Yii::app()->request->getPost('change_new_user_body'));

            $templates_new['new_pass_subject'] = str_replace("\n", '<br>', Yii::app()->request->getPost('new_pass_subject'));
            $templates_new['new_pass_body'] = str_replace("\n", '<br>', Yii::app()->request->getPost('new_pass_body'));

            $et->setTemplates($templates_new);
        }
        $templates = $et->getTemplates();

        if (!isset($templates['old_files_subject'])) {
            Yii::app()->cache->delete('email_template');
        }
        $tmp = explode('{account-info-text-if-new-acc}', $templates['buy_premium_body']);
        $pcode = explode('{premium-code}', $tmp[0]);
        $templates['buy_premium_body_1'] = $pcode[0];
        $templates['buy_premium_body_2'] = $tmp[1];
        $this->render('email_templates', array('templates' => $templates));
    }

    public function actionTechnicalPages()
    {
        $cs = Yii::app()->clientScript;
        $cs->registerCoreScript('jquery');
        $cs->registerCoreScript('cookie');
        $cs->registerCoreScript('jquery.ui');
        $cs->registerCssFile(Yii::app()->request->baseUrl . '/css/redmond/jquery-ui.css');

        $config = new Config();

        $is_under_construct = Yii::app()->request->getQuery('is_under_construct');
        $techpage_under_construct_page_title = Yii::app()->request->getPost('techpage_under_construct_page_title');

        if ($is_under_construct !== null) {
            $settings = array('techpage_is_under_construct_now' => $is_under_construct);
            $config->setSettings($settings);
            $this->redirect(Yii::app()->createUrl('Settings/TechnicalPages'));
        } elseif ($techpage_under_construct_page_title != null) {
            $arr = array(
                'techpage_under_construct_page_title' => $techpage_under_construct_page_title,
                'techpage_under_construct_page_text' => str_replace(PHP_EOL,
                                                                    '<br>',
                                                                    Yii::app()->request->getPost('techpage_under_construct_page_text')
                ),
                'techpage_error_page_title' => Yii::app()->request->getPost('techpage_error_page_title'),
                'techpage_error_page_text' => str_replace(PHP_EOL,
                                                          '<br>',
                                                          Yii::app()->request->getPost('techpage_error_page_text')
                ),
            );
            $config->setSettings($arr);
            $this->redirect(Yii::app()->createUrl('Settings/TechnicalPages'));
        }

        $this->render('technical_pages', array());
    }

    public function actionDownload()
    {
        $this->pageTitle = 'Настройка скачивания';
        $this->pageKeywords = '';
        $this->pageDescription = '';

        $mConfig = new Config();
        $form = new BackendSettingsForm('download');
        $post = Yii::app()->request->getPost('BackendSettingsForm');
        if ($post !== null) {
            $form->setAttributes($post);
            if ($form->validate()) {
                $settings = array(
                    'download_free_1' => $form->download_free_1,
                    'download_free_2' => $form->download_free_2,
                    'download_free_3' => $form->download_free_3,
                    'download_free_4' => $form->download_free_4,

                    'premiumSpeedLimit' => $form->premiumSpeedLimit,
                    'fakeFreeSpeedLimit' => $form->fakeFreeSpeedLimit,
                    'fakePremiumSpeedLimit' => $form->fakePremiumSpeedLimit,
                );
                Notifier::clearCacheOnServers();
                $mConfig->setSettings($settings);
                AutoloadDbConfig::init();
            }
        }
        $form->download_free_1 = Yii::app()->params['registry']['config']['download_free_1'];
        $form->download_free_2 = Yii::app()->params['registry']['config']['download_free_2'];
        $form->download_free_3 = Yii::app()->params['registry']['config']['download_free_3'];
        $form->download_free_4 = Yii::app()->params['registry']['config']['download_free_4'];

        $form->premiumSpeedLimit = Yii::app()->params['registry']['config']['premiumSpeedLimit'];
        $form->fakeFreeSpeedLimit = Yii::app()->params['registry']['config']['fakeFreeSpeedLimit'];
        $form->fakePremiumSpeedLimit = Yii::app()->params['registry']['config']['fakePremiumSpeedLimit'];

        $this->render('download', array('form' => $form));
    }

    public function actionRemotedl()
    {
        $this->pageTitle = 'Настройка удаленной закачки';
        $this->pageKeywords = '';
        $this->pageDescription = '';
        $clean_message = '';

        $clean = Yii::app()->request->getPost('clean');
        if ($clean == 1)
        {
            $mServer = new BackendServer();
            $mServer->remotedlStop();
            $this->actionClearCache(false);
            $remotedl_model = new RemoteDl();
            $result = $remotedl_model->getStatisticByStatus(0);
            if (!empty($result))
            {
                foreach ($result as $res)
                {
                    if (is_array($res)) {
                        if (isset($res['file_name']) && $res['file_name']!='') {
                            $file_name = $res['file_name'];
                        } else {
                            $file_name = '';
                        }

                        $remotedl_model->deleteFileById($res['id']);

                        $servers_model = new BackendServer();

                        $optimal_server = $servers_model->getById($res['server_id']);
                        if (!isset($optimal_server['http_path'])) {
                            echo 'not exist data server';
                            exit;
                        }
                        $server_url = $optimal_server['http_path'];
                        unset($json);
                        $remote_key = Yii::app()->params['download_remote']['remote_key'];
                        $json = array('file_id' => $res['id'], 'file_name' => $file_name);
                        $checksum = Generate::secureHash(json_encode($json).$remote_key);

                        $json = json_encode(array('file_id' => $res['id'], 'checksum' => $checksum, 'file_name' => $file_name));
                        unset($curl);
                        $curl = Yii::app()->CURL;
                        try {
                            $request = Yii::app()->request;
                            $origHostInfo = $request->getHostInfo();
                            $request->setHostInfo($server_url);
                            $remove_url = $server_url.'?r=RemoteDownload/stop';
                            $request->setHostInfo($origHostInfo);
                            Yii::app()->db->setActive(false);
                            $ret = $curl->run($remove_url, false, array('data' => $json));
                            $clean_message = 'Активные закачки удалены. ';
                        } catch(CException $e) {
                            $clean_message = 'Ошибка удаления активных закачек. ';
                        }
                    }
                }
            } else {
                $clean_message = 'Активные закачки удалены. ';
            }
            $clean_message.= 'Cервер остановлен.';
        }

        $mConfig = new Config();
        $form = new BackendSettingsForm('remotedl');
        $post = Yii::app()->request->getPost('BackendSettingsForm');
        if ($post !== null) {
            $form->setAttributes($post);
            if ($form->validate()) {
                $settings = array(
                    'remode_dl_free_active_downloads' => $form->remode_dl_free_active_downloads,
                    'remode_dl_free_filesize_limit' => $form->remode_dl_free_filesize_limit,
                    'remode_dl_free_speed_limit' => $form->remode_dl_free_speed_limit,
                    'remode_dl_premium_active_downloads' => $form->remode_dl_premium_active_downloads,
                    'remode_dl_premium_filesize_limit' => $form->remode_dl_premium_filesize_limit,
                    'remode_dl_premium_speed_limit' => $form->remode_dl_premium_speed_limit,
                );
                Notifier::clearCacheOnServers();
                $mConfig->setSettings($settings);
                AutoloadDbConfig::init();
            }
        }
        $form->remode_dl_free_active_downloads = Yii::app()->params['registry']['config']['remode_dl_free_active_downloads'];
        $form->remode_dl_free_filesize_limit = Yii::app()->params['registry']['config']['remode_dl_free_filesize_limit'];
        $form->remode_dl_free_speed_limit = Yii::app()->params['registry']['config']['remode_dl_free_speed_limit'];
        $form->remode_dl_premium_active_downloads = Yii::app()->params['registry']['config']['remode_dl_premium_active_downloads'];
        $form->remode_dl_premium_filesize_limit = Yii::app()->params['registry']['config']['remode_dl_premium_filesize_limit'];
        $form->remode_dl_premium_speed_limit = Yii::app()->params['registry']['config']['remode_dl_premium_speed_limit'];

        $this->render('remotedl', array('form' => $form, 'clean_message' => $clean_message));
    }

    public function actionUpload()
    {
        $this->pageTitle = 'Настройка загрузки';
        $this->pageKeywords = '';
        $this->pageDescription = '';

        $mServer = new BackendServer();
        $form = new BackendSettingsForm('upload');
        $req = Yii::app()->request;
        $post = $req->getPost('BackendSettingsForm');
        $servers = $mServer->getAll();
        if ($post !== null) {
            $transaction = Yii::app()->db->beginTransaction();
            try {
                foreach ($servers as $server) {
                    $arr = array(
                        'web_upload_enabled' => $req->getPost('web_upload_enabled_server_' . $server['id']) ? 1: 0,
                        'ftp_upload_enabled' => $req->getPost('ftp_upload_enabled_server_' . $server['id']) ? 1: 0,
                        'remote_upload_enabled' => $req->getPost('rmt_upload_enabled_server_' . $server['id']) ? 1: 0,
                    );
                    $mServer->update($arr, 'id=:id', array(':id' => $server['id']));
                }
                $transaction->commit();
            } catch (Exception $e) {
                $transaction->rollback();
                Yii::app()->user->setFlash('error', $e->getMessage());
                // throw new CHttpException(500, "Ошибка при сохранении в БД: " . $e->getMessage());
            }
            try {
                Yii::app()->cache->delete('web_upload_enabled_server');
                Yii::app()->cache->delete('ftp_upload_enabled_server');
                Yii::app()->cache->delete('remote_upload_enabled_server');
                Yii::app()->cache->delete('data_servers');
                Notifier::clearCacheOnServers();
            } catch (Exception $e) {
                throw new CHttpException(500, "Ошибка при очистке кеша на датасерверах. Необходимо еще раз сохранить настройки. Детали ошибки: " . $e->getMessage());
            }
            Yii::app()->user->setFlash('success', "Настройки сохранены");
        }
        $servers = $mServer->getAll();
        $form->upload_servers = $servers;

        $this->render(
            'upload',
            array(
                 'form' => $form,
            )
        );
    }

    public function actionApcMonitoring()
    {
        $this->pageTitle = 'Мониторинг APC';
        $this->pageKeywords = '';
        $this->pageDescription = '';

        $mServer = new BackendServer();
        $all_servers = $mServer->getAll();

        $selected_server = Yii::app()->request->getQuery('server');
        if ($selected_server > 0) {
            $selected_server_info = $mServer->getById($selected_server);
            $selected_server_name = $selected_server_info['http_path'];
        } else {
            $selected_server_info['http_path'] = 'http://'.str_replace('backend.','',$_SERVER['SERVER_NAME']).'/';
            $selected_server_name = 'Web site';
        }
        $link = $selected_server_info['http_path'].'apc040404.php';

        $this->render('apc_monitoring', array('all_servers' => $all_servers, 'selected_server_name' => $selected_server_name, 'link' => $link));
    }
}
